//
//  ForgetPasswordViewController.m
//  JiuLe
//
//  Created by SunChao on 16/11/15.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "ForgetPasswordViewController.h"
#import "MallRequestManager.h"
@interface ForgetPasswordViewController ()<UITextFieldDelegate>

@property (nonatomic,strong)IBOutlet UITextField *textPhoneNum;//手机号
@property (nonatomic,strong)IBOutlet UITextField *textVerification;//验证码
@property (nonatomic,strong)IBOutlet UITextField *textNewPassword;//新密码
@property (nonatomic,strong)IBOutlet UITextField *textConfirm;//确认密码
@property (nonatomic,strong)IBOutlet UIButton *btnConfirm;//确认密码
@property (nonatomic,strong)IBOutlet UIButton *btnVerification;//确认密码
@property (nonatomic,assign)int secondsCountDown;
@property (nonatomic,strong)NSTimer *countDownTimer;
@end

@implementation ForgetPasswordViewController
- (IBAction)confirmAction:(UIButton *)sender
{
    if (![self isMobile:self.textPhoneNum.text]) {
        [SVProgressHUD showErrorWithStatus:@"手机号码输入错误"];
    }else if (self.textVerification.text.length==0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
    }
    else if (self.textNewPassword.text.length ==0||self.textConfirm.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入新密码"];
    }else if (self.textNewPassword.text.length<6)
    {
        [SVProgressHUD showErrorWithStatus:@"密码必须大于6位"];
    }else if (!([self.textNewPassword.text isEqualToString:self.textConfirm.text]))
    {
        [SVProgressHUD showErrorWithStatus:@"两次密码不一致"];
    }else
    {
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setObject:self.textPhoneNum.text forKey:@"mobile"];
        [params setObject:self.textVerification.text forKey:@"code"];
        [params setObject:self.textNewPassword.text forKey:@"password"];
        [MallRequestManager post:@"Personinfo/forgetpassword" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([dic.allKeys containsObject:@"status"]) {
                if (![[[dic objectForKey:@"status"] stringValue]isEqualToString:@"200"]) {
                    [SVProgressHUD showErrorWithStatus:[dic objectForKey:@"message"]];
                }else
                {
                    [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"message"]];
                    [self performSelectorOnMainThread:@selector(backTo) withObject:nil waitUntilDone:YES];
                }
            }
        }];
    }
}
-(void)timeFireMethod{
    
    _secondsCountDown--;
    NSString *title = [NSString stringWithFormat:@"%ds",_secondsCountDown];
    [self.btnVerification setTitle:title forState:UIControlStateDisabled];
    if(_secondsCountDown==0){
        [_countDownTimer invalidate];
        self.btnVerification.enabled = YES;
        [self.btnVerification setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}
- (IBAction)verificationAction:(UIButton *)sender
{
     self.btnVerification.enabled = NO;
     BOOL result = [self isMobile:self.textPhoneNum.text];
    if (result) {
        //发送请求
        NSDictionary *params = [NSMutableDictionary new];
        [params setValue:self.textPhoneNum.text forKey:@"mobile"];
        [MallRequestManager post:@"Personinfo/forgetsmsrequest" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) {
                [SVProgressHUD showErrorWithStatus:@"数据请求失败"];
            }else
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if ([dic.allKeys containsObject:@"message"]) {
                    [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"message"]];
                   
                    [self performSelectorOnMainThread:@selector(reloadUI) withObject:nil waitUntilDone:YES];
                }
            }
        }];
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        self.btnVerification.enabled = YES;
    }
}
- (void)reloadUI
{
    _secondsCountDown = 60;//60秒倒计时
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = NO;
    self.navigationController.navigationBarHidden = NO;
    self.title = @"忘记密码";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    self.textPhoneNum.keyboardType = UIKeyboardTypeNumberPad;
    self.textVerification.keyboardType = UIKeyboardTypeNumberPad;
    [self.textNewPassword setSecureTextEntry:YES];
    [self.textConfirm setSecureTextEntry:YES];
    [self.btnConfirm setBackgroundColor:RGB(0, 172, 238)];
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, self.view.frame.size.width, 30)];
        [view addSubview:label];
        label.text = @"请输入您激活时的手机";
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:13];
        return view;
    }else
    {
        return nil;
    }
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 50;
    }else if (section == 1)
    {
        return 15;
    }
    return 0;
}

/**
 *  手机号码验证
 *
 *  @param mobileNumbel 传入的手机号码
 *
 *  @return 格式正确返回true  错误 返回fals
 */
- (BOOL) isMobile:(NSString *)mobileNumbel{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}
@end
